package com.cmcc.linlaker.ui.upload;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.cmcc.linlaker.R;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.ImageUploadBean;
import com.cmcc.linlaker.crop.ClipImageActivity;
import com.cmcc.linlaker.crop.util.ActivityResultHelper;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.permission.GPermisson;
import com.cmcc.linlaker.permission.PermissionCallback;
import com.cmcc.linlaker.ui.query.ImageScanActivity;
import com.cmcc.linlaker.ui.query.bean.ProjectDetailBean;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter;
import com.cmcc.linlaker.ui.upload.adapter.ImageAdapter2;
import com.cmcc.linlaker.ui.upload.bean.ImageBean;
import com.cmcc.linlaker.ui.upload.bean.UploadQuestionBean;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.DensityUtil;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.PhotoUtils;
import com.cmcc.linlaker.utils.PictureUtil;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.StringUtils;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.view.GridSpacingItemDecoration;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class UploadSelfDealDetailActivity extends AppCompatActivity {
    private UploadQuestionBean.UploadQuestionData problemBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_self_deal_detail);

        BarUtils.initStatusBar(this);

        problemBean = (UploadQuestionBean.UploadQuestionData) getIntent().getSerializableExtra("problemBean");

        initView();
    }

    private ImageAdapter2 adapter;
    private ArrayList<String> imageList = new ArrayList<>();
    private RecyclerView recycler_pic;

    private TextView text_title, text_code, text_address, text_date, text_person_name, text_project_name, text_pic_desc;

    private ImageAdapter adapter2;
    private List<ImageBean> bmpList = new ArrayList<>();
    private RecyclerView recycler_pic_2;

    private TextView text_input_info;
    private EditText edit_description;

    public void initView() {
        recycler_pic = findViewById(R.id.recycler_pic);
        setRecyclerView(recycler_pic, imageList);

        text_title = findViewById(R.id.text_title);
        text_code = findViewById(R.id.text_code);
        text_address = findViewById(R.id.text_address);
        text_date = findViewById(R.id.text_date);
        text_person_name = findViewById(R.id.text_person_name);
        text_project_name = findViewById(R.id.text_project_name);
        text_pic_desc = findViewById(R.id.text_pic_desc);

        recycler_pic_2 = findViewById(R.id.recycler_pic_2);
        setRecyclerView2(recycler_pic_2, bmpList);

        addButton();

        text_input_info = findViewById(R.id.text_input_info);
        edit_description = findViewById(R.id.edit_description);
        edit_description.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = edit_description.getText().toString();
                int length = content.length();
                text_input_info.setText(length + "/100");
            }
        });

        if (problemBean != null) {
            getProblemDetail();
        }
    }


    private void setRecyclerView2(final RecyclerView recycler_view, final List<ImageBean> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(this, 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(this, 10), true));
        adapter2 = new ImageAdapter(this, itemList);
        adapter2.setOnItemClickListener(new ImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (itemList.get(position).type == 0) {
                    selectPictures();
                } else {
                    Intent intent = new Intent(UploadSelfDealDetailActivity.this, ImageScanActivity.class);
                    intent.putExtra("imageList", imageList);
                    intent.putExtra("position", position);
                    startActivity(intent);
                }
            }

            @Override
            public void onItemDeleteClick(int position) {
                deletePic(position);
            }
        });
        recycler_view.setAdapter(adapter2);
    }

    /**
     * 选择图片
     */
    public void selectPictures() {
        if (Build.VERSION.SDK_INT >= 23) {
            GPermisson.with(this)
                    .permisson(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
                    .callback(new PermissionCallback() {
                        @Override
                        public void onPermissionGranted() {
                            showSelectDialog();
                        }

                        @Override
                        public void shouldShowRational(String permisson) {
                        }

                        @Override
                        public void onPermissonReject(String permisson) {
                        }
                    }).request();
        } else {
            showSelectDialog();
        }

    }

    private void showSelectDialog() {
        final String[] items = {"相机", "相册"};
        AlertDialog.Builder builder = new AlertDialog.Builder(
                this);
        builder.setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (which == 0) {// 相机
                            takePhoto();
                        } else if (which == 1) {// 相册
                            choosePhoto();
                        }

                    }
                }).create().show();
    }

    public static final int RC_TAKE_PHOTO = 1;
    public static final int RC_CHOOSE_PHOTO = 2;
    public static final int RC_CROP_PHOTO = 3;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/lh_crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;

    /**
     * 拍照
     */
    private void takePhoto() {
        imageUri = Uri.fromFile(fileUri);
        //通过FileProvider创建一个content类型的Uri
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(this, "com.cmcc.linlaker.fileprovider", fileUri);
        }

        PhotoUtils.takePicture(this, imageUri, RC_TAKE_PHOTO);
    }

    /**
     * 打开相册
     */
    private void choosePhoto() {
        PhotoUtils.openPic(this, RC_CHOOSE_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_TAKE_PHOTO) {

//                cropImageUri = Uri.fromFile(fileCropUri);
                gotoClipActivity(Uri.fromFile(fileUri));
//                PhotoUtils.fragmentCropImageUri(this, imageUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CHOOSE_PHOTO) {
                cropImageUri = Uri.fromFile(fileCropUri);
//                Uri newUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    newUri = FileProvider.getUriForFile(getActivity(), "com.cmcc.linlaker.fileprovider", new File(newUri.getPath()));
//                }
                gotoClipActivity(data.getData());
//                PhotoUtils.fragmentCropImageUri(this, newUri, cropImageUri, 1, 1, LoadingActivity.screenWidth, LoadingActivity.screenWidth, RC_CROP_PHOTO);
            } else if (requestCode == RC_CROP_PHOTO) {
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        }
    }

    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        ClipImageActivity.goToClipActivity(this, uri, new ActivityResultHelper.Callback() {
            @Override
            public void onActivityResult(int resultCode, Intent intent) {
                if (intent == null) {
                    return;
                }

                final Uri uri = intent.getData();
                if (uri == null) {
                    return;
                }
                Bitmap myBitmap = PhotoUtils.getBitmapFromUri(uri, UploadSelfDealDetailActivity.this);

                String fileName = PictureUtil.getCharacterAndNumber();
                File file = new File(PictureUtil.PHOTO_DIR, fileName + ".png");
                PictureUtil.saveMyBitmap(myBitmap, file);

                addBmp(myBitmap);

                uploadPic(fileName + ".png", file);
            }
        });
    }


    private List<ImageUploadBean> imageList2 = new ArrayList<>();

    private void uploadPic(String fileName, File file) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post()
                .headers(headers)
                .addFile("file", fileName, file)
                .url(ApiDefine.UPLOAD_PIC)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onError:", "onError");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("url:", response);
                        String jsonStr = response;
                        Gson gson = new GsonBuilder().create();
                        ImageUploadBean bean = gson.fromJson(jsonStr, new TypeToken<ImageUploadBean>() {
                        }.getType());

                        if (bean != null) {
                            imageList2.add(bean);
                        }

                    }
                });
    }


    /**
     * 删除图片
     */
    private void deletePic(int position) {
        imageList2.remove(position);
        bmpList.remove(position);

        adapter2.notifyDataSetChanged();
    }

    /**
     * 添加按钮
     */
    private void addButton() {
        ImageBean bean = new ImageBean();
        bean.type = 0;
        bmpList.add(bean);

        adapter2.notifyDataSetChanged();
    }

    /**
     * 添加图片
     */
    private void addBmp(Bitmap bmp) {
        ImageBean bean = new ImageBean();
        bean.bitmap = bmp;
        bean.path = StringUtils.bitmaptoString(bmp);
        bean.type = 1;
        bmpList.add(bmpList.size() - 1, bean);

        adapter2.notifyDataSetChanged();
    }


    private void setRecyclerView(final RecyclerView recycler_view, final ArrayList<String> itemList) {
        recycler_view.setHasFixedSize(true);
        recycler_view.setLayoutManager(new GridLayoutManager(this, 4));

        recycler_view.setNestedScrollingEnabled(false);
        recycler_view.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(this, 10), true));
        adapter = new ImageAdapter2(this, itemList);
        adapter.setOnItemClickListener(new ImageAdapter2.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(UploadSelfDealDetailActivity.this, ImageScanActivity.class);
                intent.putExtra("imageList", itemList);
                intent.putExtra("position", position);
                startActivity(intent);

//                BigImageDialog dialog = new BigImageDialog(UploadDetailActivity.this, R.style.dialog, itemList.get(position));
//                dialog.setCanceledOnTouchOutside(true);
//                dialog.show();
            }
        });
        recycler_view.setAdapter(adapter);
    }

    public void back(View view) {
        finish();
    }

    /**
     * 获取详情
     */
    private void getProblemDetail() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        String url = ApiDefine.PROBLEM_DETAIL + problemBean.id;
        helper.sendGETRequest(url, UploadQuestionBean.UploadQuestionDetailData.class, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    UploadQuestionBean.UploadQuestionDetailData bean = (UploadQuestionBean.UploadQuestionDetailData) data;
                    if (bean.code.equals("0")) {
                        UploadQuestionBean.UploadQuestionData detailData = bean.data;
                        text_title.setText(detailData.title);
                        text_code.setText(detailData.serialNumber);
                        text_address.setText(detailData.reportPlace);
                        text_date.setText(detailData.reportTime);
                        text_person_name.setText(detailData.createBy);
                        if (!TextUtils.isEmpty(detailData.description)) {
                            findViewById(R.id.rl_desc).setVisibility(View.VISIBLE);
                            text_pic_desc.setText(detailData.description);
                        } else {
                            findViewById(R.id.rl_desc).setVisibility(View.GONE);
                        }

                        if (detailData.problemPhotos != null && detailData.problemPhotos.size() > 0) {
                            findViewById(R.id.text_no_photo).setVisibility(View.GONE);
                            recycler_pic.setVisibility(View.VISIBLE);
                            imageList.clear();
                            for (int i = 0; i < detailData.problemPhotos.size(); i++) {
                                imageList.add(detailData.problemPhotos.get(i).fastDfsServer + detailData.problemPhotos.get(i).groupName + "/" + detailData.problemPhotos.get(i).photoUrl);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            findViewById(R.id.text_no_photo).setVisibility(View.VISIBLE);
                            recycler_pic.setVisibility(View.GONE);
                        }
                        if (!TextUtils.isEmpty(detailData.projectId)) {
                            findViewById(R.id.layout_project).setVisibility(View.VISIBLE);
                            getProjectDetail(detailData.projectId);
                        } else {
                            findViewById(R.id.layout_project).setVisibility(View.VISIBLE);
                            text_project_name.setText("无");
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(UploadSelfDealDetailActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 查询详情
     */
    private void getProjectDetail(String projectId) {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        String getUrl = ApiDefine.PROJECT_DETAIL + projectId;
        helper.sendGETRequest(getUrl, ProjectDetailBean.class, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    ProjectDetailBean bean = (ProjectDetailBean) data;
                    if (bean.code.equals("0")) {
                        text_project_name.setText(bean.data.name);
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(UploadSelfDealDetailActivity.this);
                    } else {

                    }
                }
            }
        });
    }

    public void selfDeal(View view) {

        if (imageList2.size() < 2) {
            ToastUtils.showText(this, "请至少上传处置后一张近景照片和一张远景照片");
            return;
        }

        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("remark", edit_description.getText().toString());
        params.put("problemId", problemBean.id);
        params.put("afterUrl", getImageListStr());

        helper.sendPOSTRequest(ApiDefine.SELF_DEAL, BaseBean.class, params, true, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;
                    if (bean.code.equals("0")) {
                        ToastUtils.showText(UploadSelfDealDetailActivity.this, "自行处置上传成功");

                        setResult(3000);
                        finish();
                    } else {
                        ToastUtils.showText(UploadSelfDealDetailActivity.this, bean.msg);
                    }
                }
            }
        });
    }

    /**
     * 获取图片url
     */
    private String getImageListStr() {
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < imageList2.size(); i++) {
            ImageUploadBean bean = imageList2.get(i);

            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("fileOwn", "afterUrl");
                jsonObject.put("groupName", bean.groupName);
                jsonObject.put("extName", bean.extName);
                jsonObject.put("fileName", bean.fileName);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        return jsonArray.toString();
    }
}
